var express = require('express');
var router = express.Router();
// 加密模块 
const crypto = require('crypto');
// token
const jwt = require("jsonwebtoken");
// 全球唯一码(提供两个方法用于设置v1和v4的级别)
const uuid = require("node-uuid");
// 小程序需要在服务端请求的模块实现
// const request = require("request");

// 导入sql函数
const sql = require("../utils/sql");
// 导入schema
const {
  Uid0,
  Vuer,
  Coupon
} = require('../mongodb/schema.js');

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('我是users路由的首页返回值');
});

/**
 * @api {post} /users/reg 注册接口
 * @apiDescription 注册接口
 * @apiGroup users
 * @apiName register-user
 * @apiParam { String } username User's name
 * @apiParam { String } phone User's phone
 * @apiParam { String } password User's password
 * @apiSuccessExample { json } Success-response:
 * res.json({
      code: 200,
      status: 0,
      msg: '注册成功',
      result
    })
    res.json({
      code: 200,
      status: -1,
      msg: '用户已注册',
      result: null
    })
    res.json({
      code: 200,
      status: -1,
      msg: '信息不完善,操作失败',
      result: null
    })
 * @apiSampleRequest /users/reg
 * @apiVersion 1.0.0
 */
router.post("/reg", (req, res, next) => {
  let { username, phone, password } = req.body;
  if (!(phone.trim()) || !(password.trim())) {
    res.json({
      code: 200,
      status: -1,
      msg: '信息不完善,操作失败',
      result: null
    })
    return
  }
  Vuer.find({ phone }, {_id:0,__v:0}).then((response) => {
    if (response.length > 0) {
      // 表示用户已经存在
      res.json({
        code: 200,
        status: -1,
        msg: '用户已注册',
        result: null
      })
    }
    else {
      Uid0.updateOne({
        // 先存(刚开始是id:0;直接取是从0开始的,等更新后再取)
        username: "uniers"
      }, {
        $inc: {
          id: 1
        }
      }).then(() => {
        Uid0.findOne({
          username: "uniers"
        }, {_id:0,__v:0}).then(updateUid => {
          // 对password进行加密
          const hash = crypto.createHmac('sha256', password)
            .update('hybrid')
            .digest('hex');
          const time = new Date().getTime();
          Vuer({
            username,
            phone,
            password: hash,
            uid: updateUid.id,
            createTime: time,
            userid: "uni_" + uuid.v1(),
            member: time,
            avatar: '',
            token: '',
            poster: ''
          }).save().then((result) => {
            res.json({
              code: 200,
              status: 0,
              msg: '注册成功',
              result
            })
          })
        })
      })
    }
  })
})

/**
 * @api {post} /users/quit 退出登录接口
 * @apiDescription 退出登录接口
 * @apiGroup users
 * @apiName quit-user
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: '成功退出登录',
    result: null
   })
 * @apiSampleRequest /users/quit
 * @apiVersion 1.0.0
 */
router.post("/quit", (req, res) => {
  // 一般在前端清token
  req.session.user = "";
  req.session.userid = "";
  if (req.cookies.token) {
    res.cookie("token", "")
  }
  res.json({
    code: 200,
    status: 0,
    msg: '成功退出登录',
    result: null
  })
})

/**
 * 小程序登录
 */
// router.get("/login",(req,res)=>{
// 	var code = req.query.code;
// 	var id ='wx92a5a8eeaf5802ff';  //appid
// 	var secret ='98828f2f5887455fb18b21a1c596b113'; //appsecret
// 	var url=`https://api.weixin.qq.com/sns/jscode2session?appid=${id}&secret=${secret}&js_code=${code}&grant_type=authorization_code`
// 	request.get(url,(err,response,body)=>{
// 		var obj =JSON.parse(body);  //body里就含有openid session_key
// 		 var token = jwt.sign({username:obj.openid,time:Date.now()},"haha",{expiresIn:10000});
// 		res.json({   //登录成功
// 			status:0,
// 			 data:{
// 			 	login:true,
// 				 token
// 			 }
// 		})
// 	})
// })

/**
 * @api {post} /users/login 登录接口
 * @apiDescription 登录接口
 * @apiGroup users
 * @apiName login-user
 * @apiParam { String } phone User's phone
 * @apiParam { String } password User's password
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "登陆成功",
    result: {
      login: true,
      token
    }
  })
  res.json({
    code: 200,
    status: -1,
    msg: "用户名或者密码错误",
    result: null
  })
  res.json({
    code: 200,
    status: -1,
    msg: "该用户尚未注册",
    result: null
  })
  res.json({
    code: 200,
    status: -1,
    msg: '信息不完善,操作失败',
    result: null
  })
 * @apiSampleRequest /users/login
 * @apiVersion 1.0.0
 */
router.post("/login", (req, res) => {
  let { phone, password } = req.body;
  if (!(phone.trim()) || !(password.trim())) {
    res.json({
      code: 200,
      status: -1,
      msg: '信息不完善,操作失败',
      result: null
    })
    return
  }
  // 对password进行加密
  const hash = crypto.createHmac('sha256', password)
    .update('hybrid')
    .digest('hex');
  // 查找为0则不显示
  sql.find(Vuer, { phone }, {_id:0,__v:0}).then((response) => {
    if (response.length > 0) {
      if (response[0].password === hash) {
        // console.log(response[0].password, hash, response[0].password === hash)
        // 把登录成功的用户名放到session里(清除了没用,只要前端带了token,还是校验通过)
        req.session.user = phone;
        req.session.userid = response[0].userid;
        // 制作令牌
        let token = jwt.sign({ phone, userid: response[0].userid, time: Date.now() }, "uni-app", { expiresIn: 10000 });
        res.cookie("token", token);
        res.json({
          code: 200,
          status: 0,
          msg: "登陆成功",
          result: {
            login: true,
            token,
            userinfo: response[0]
          }
        })
      } else {
        res.json({
          code: 200,
          status: -1,
          msg: "用户名或者密码错误",
          result: null
        })
      }
    } else {
      // 登录失败
      res.json({
        code: 200,
        status: -1,
        msg: "该用户尚未注册",
        result: null
      })
    }
  })
})

/**
 * 添加优惠券种类
 */
router.post("/add-coupon", (req, res) => {
  const {
    id,
    condition,
    valueDesc,
    unitDesc,
    name,
    startAt,
    num,
    description,
    reason
  } = req.body;
  Coupon.insertMany({
    id,
    condition,
    value: valueDesc * 100,
    valueDesc: valueDesc+'',
    unitDesc: unitDesc || '元',
    startAt: startAt/1000,
    endAt:startAt/1000+(num*24*60*60),
    name,
    description,
    reason
  }).then(response=>{
    res.json({
      code: 200,
      status: 0,
      msg: '添加优惠券成功',
      result: response
    })
  })
})

router.get("/get-coupon", (req,res)=>{
  Coupon.find({},{_id:0,__v:0}).then(response=>{
    res.json({
      code: 200,
      status: 0,
      msg: '获取优惠券成功',
      result: response
    })
  })
})

module.exports = router;
